package com.example.exam.servlet;

import com.example.exam.dao.ScoreDAO;
import com.example.exam.entity.Score;
import com.example.exam.entity.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 成绩Servlet
 */
@WebServlet("/scores")
public class ScoreServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private ScoreDAO scoreDAO = new ScoreDAO();
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 检查用户是否已登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("student") == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        
        // 获取学生ID
        String studentId = ((Student) session.getAttribute("student")).getStudentId();
        
        // 获取查询参数
        String keyword = request.getParameter("keyword");
        
        List<Score> scores;
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            // 搜索成绩
            scores = scoreDAO.getScoresByStudentId(studentId);
            // 在内存中过滤
            scores.removeIf(score -> !score.getExam().getExamName().toLowerCase().contains(keyword.trim().toLowerCase()));
        } else {
            // 获取所有成绩
            scores = scoreDAO.getScoresByStudentId(studentId);
        }
        
        // 计算平均分
        double averageScore = 0;
        if (scores != null && !scores.isEmpty()) {
            double totalScore = 0;
            for (Score score : scores) {
                totalScore += score.getScore();
            }
            averageScore = totalScore / scores.size();
        }
        
        // 转发到成绩页面
        request.setAttribute("scores", scores);
        request.setAttribute("averageScore", averageScore);
        request.getRequestDispatcher("/WEB-INF/views/scores.jsp").forward(request, response);
    }
}    